package be.rubengerits.test;

import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import be.rubengerits.test.objects.*;
import java.io.*;
import java.lang.reflect.*;

import java.lang.Process;
import android.text.method.*;

public class MainActivity extends Activity {

	private static Context context; 

	private TextView log;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MainActivity.context = getApplicationContext();

		setContentView(R.layout.main);

		log = (TextView) findViewById(R.id.log);
		log.setMovementMethod(new ScrollingMovementMethod());
	}

	public void refresh(View v) throws Exception {
		StringBuilder output = new StringBuilder();

		InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.directions));
		JsonReader reader = new JsonReader(inputStream);

		try {
			reader.beginObject();
			GoogleDirections directions = new GoogleDirections();
			String childName = reader.nextName();
			Class<?> c = JsonFactory.getChildClass(directions, childName);
			JsonObject object = JsonFactory.parseObject(childName, reader, c, directions);
			reader.endObject();
		} catch (Exception e) {
			output.append("ERROR: ");
			output.append(e.getMessage());
			output.append("\nSTACKTRACE:\n");
			output.append(Log.getStackTraceString(e));
			output.append("\nLOGCAT\n");
			try {
				output.append(logcat());
			} catch (Exception ex) {
				output.append(Log.getStackTraceString(ex));
			}
		} finally {
			reader.close();
		}

		log.setText(output.toString());

	}

	public static Context getAppContext() {
		return MainActivity.context;
	}

	public String logcat() throws IllegalArgumentException, IOException {
		Process process = Runtime.getRuntime().exec("logcat -d");

		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

		String output = "";
		try {
			String line;
			while ((line = reader.readLine()) != null) {
				output += line + "\n";
			}
		} catch (IOException e) {}
		return output;
	}
}
